package com.wujunshen.algorithm.leetcode.basic;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/24 21:04<br>
 */
public class 链表中倒数第k个节点 {
  public ListNode getKthFromEnd(ListNode head, int k) {
    int length = 0;
    ListNode tmp = head;
    while (tmp != null) {
      tmp = tmp.next;
      length++;
    }
    return getKGroupEnd(head, length - k + 1);
  }

  private ListNode getKGroupEnd(ListNode head, int k) {
    while (--k != 0 && head != null) {
      head = head.next;
    }
    return head;
  }
}
